<?php


namespace App\Services\PosApi;


use App\Services\Oms\ApiService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Order
{
    public function confirm($type, $orderNo, $refundNo = '')
    {
        if ($type == 1) {
            $params = $this->orderConfirm($orderNo);
            if (empty($params)){
                return ['error' => true, 'message' => '未查询到有效订单'];
            }
        } else {
            $params = $this->refundConfirm($orderNo, $refundNo);
            if (empty($params)){
                return ['error' => true, 'message' => '未查询到有效退款单'];
            }
        }

        $shopInfo = DB::table('pos_core.store')
            ->where('id','=',$params['shop_bn'])
            ->first();
        $data = [
            'method' => $type == 1 ? 'd1mpos.order.add' : 'd1mpos.order.return',
            'brand_bn' => (empty($shopInfo) || empty($shopInfo->brand_no)) ? 'd1m' : $shopInfo->brand_no,
            'params' => json_encode($params)
        ];
        $omsApi = new ApiService();
        $result = $omsApi->requestOMS($data);
        return (empty($result['code']) || $result['code'] != 200) ? ['error' => true, 'message' => $result['message']] : ['error' => false];
    }

    public function orderConfirm($orderNo)
    {
        $field = ['order.no as order_bn','order.shop_id as shop_bn','order.order_time as createtime','order.pay_time as paytime','payment.payment_method as pay_bn',
            'tender.tender_sn as trade_no','order.amount as order_price','order.pay_amount as pay_amount','order.should_amount as cost','order.reduce_amount as pmt_order','order.remark as order_memo',
            'sku.bar_code as bn', 'goods.qty as num','goods.show_name as name','cost.amount as price','cost.wechat_amount as sale_price','cost.should_amount as should_amount',
            'user.real_name as name','user.phone as mobile','user.manage_no as manage_no'];
        $orderDetailList = DB::table('pos_core.order_record as order')
            ->where('order.no', '=', $orderNo)
            ->where(function($query){
                $query->where('order.state','=',5)->orWhere(function($query){
                    $query->where('order.state','=',7);
                });
            })
            ->join('pos_core.order_cost as cost', 'cost.no', '=', 'order.no')
            ->join('pos_core.order_cost_retail_product as goods', 'cost.id', '=', 'goods.order_cost_id')
            ->leftJoin('pos_core.product_spec_retail_online as spec', 'spec.id', '=', 'cost.business_id')
            ->leftJoin('pos_core.product_spec as sku', 'sku.id', '=', 'spec.product_spec_id')
            ->join('pos_payment.combined_payment as combined',function ($join){
                $join->on(DB::Raw('combined.business_order_no COLLATE utf8mb4_general_ci'),'=','order.no')->where('combined.status','=','paid');
            },null,null,'left' )
            ->leftJoin('pos_payment.payment as payment','payment.combined_payment_id','=','combined.id')
            ->join('pos_payment.shouqianba_payment_tender as tender',function ($join){
                $join->on('tender.payment_id','=','payment.id')->where('tender.pay_status','=',3);
            },null,null,'left' )
            ->leftJoin('pos_core.user_app as user', 'user.manage_no', '=', 'order.buy_user')
            ->get($field)->toArray();
        Log::info("推单调试4：".json_encode($orderDetailList));
        if (empty($orderDetailList)) {
            return [];
        }
        Log::info("推单调试3：".json_encode($orderDetailList));

        $list = [];
        foreach ($orderDetailList as $key => $val) {
            if (empty($val->bn)){
                $val->bn = 'temporary_goods_from_d1m-pos';
            }
            $val->sale_price = $val->price /$val->num / 100;
            $val->discounts_order = ($val->price - $val->should_amount) /100;
            $val->price = $val->price /$val->num / 100;
            $val->pay = $val->should_amount/ 100;
            $val->discounts = 0;
            $orderPrice = $val->order_price;
            $val->order_price = $val->order_price/100;
            if (empty($list['products'])) {
                $list['products'] = [];
                $list['products'] = array_merge((array)$list['products'], [(array)$val]);
                $list['order_bn'] = $val->order_bn;
                $list['shop_bn'] = $val->shop_bn;
                $list['createtime'] = strtotime($val->createtime);
                $list['paytime'] = strtotime($val->paytime);
                $list['pay'] = [[
                    'pay_bn' => empty($val->pay_bn) ? 'cash' : $val->pay_bn,
                    'pay_amount' => $val->pay_amount/100,
                    'trade_no' => empty($val->trade_no) ? '' : $val->trade_no
                ]];
                $list['cost'] = $val->cost/100;
                $list['pmt_order'] = ($orderPrice - $val->cost)/100;
                $list['pmt_goods'] = 0;
                $list['order_memo'] = $val->order_memo;
                $list['is_tax'] = false;
                $list['order_refer_source'] = 'offline';
                $list['is_anonymity'] = empty($val->user_manage_no) ? true : false;
                $list['account'] = [
                    'name' => $val->name,
                    'mobile' => $val->mobile,
                ];
            } else {
                $list['products'] = array_merge((array)$list['products'], [(array)$val]);
            }
        }
        Log::info("推单调试1：".json_encode($orderDetailList));
        Log::info("推单调试2：".json_encode($list));
        return $list;
    }

    public function refundConfirm($orderNo, $refundNo)
    {
        $field = ['refund.no as order_bn', 'refund.refund_no as return_bn', 'refund.refund_time as createtime', 'refund.refund_amount as amount', 'order.shop_id as shop_bn', 'sku.bar_code as bn', 'goods.qty as num'];
        $refundList = DB::table('pos_core.order_refund as refund')
            ->where('refund.no', '=', $orderNo)
            ->where('refund.refund_no', '=', $refundNo)
            ->where('refund.state','=',2)
            ->join('pos_core.order_record as order','order.no','=','refund.no')
            ->join('pos_core.order_cost as cost', 'cost.no', '=', 'refund.no')
            ->join('pos_core.order_cost_retail_product as goods', 'cost.id', '=', 'goods.order_cost_id')
            ->leftjoin('pos_core.product_spec_retail_online as spec', 'spec.id', '=', 'cost.business_id')
            ->leftjoin('pos_core.product_spec as sku', 'sku.id', '=', 'spec.product_spec_id')
            ->get($field)->toArray();
        if(empty($refundList)){
            return [];
        }

        $list = [];
        foreach ($refundList as $key=>$val) {
            if (empty($list['products'])) {
                $list['products'] = [];
                $list['products'] = array_merge((array)$list['products'], [(array)$val]);
                $list['order_bn'] = $val->order_bn;
                $list['return_bn'] = $val->return_bn;
                $list['shop_bn'] = $val->shop_bn;
                $list['type'] = 1;
                $list['amount'] = $val->amount / 100;
                $list['createtime'] = strtotime($val->createtime);
            } else {
                $list['products'] = array_merge((array)$list['products'], [(array)$val]);
            }
        }
        return $list;
    }
}